<template>
  <div v-if="data && data.list.length >= 0">
    <a-form-model ref="form" :model="models" :rules="rules">
      <template v-for="item in data.list">
        <template v-if="item.type === 'grid'">
          <a-row
            :key="item.key"
              type="flex"
              :gutter="item.options.gutter > 0 ? item.options.gutter : 0"
              :justify="item.options.justify"
              :align="item.options.align"
            >
              <a-col v-for="(col, colIndex) in item.columns" :key="colIndex" :span="col.span ? col.span : 0">
                <template v-for="citem in col.list">
                  <generate-form-item :widget="citem" :key="citem.key" :models.sync="models" :rules="col.rules" @change="handleChange"/>
                </template>
              </a-col>
          </a-row>
        </template>
        <template v-else>
          <generate-form-item :widget="item" :key="item.key" :models.sync="models" :rules="item.rules" @change="handleChange"/>
        </template>
      </template>
    </a-form-model>
  </div>
</template>

<script>
import GenerateFormItem from './GenerateFormItem.vue'
export default {
  name: 'GenerateForm',
  components: { GenerateFormItem },
  props: ['data', 'value'],
  data() {
    return {
      models: {},
      rules: {},
    }
  },
  created() {
    this.generateModel(this.data.list);
  },
  methods: {
    generateModel(formEleList){
      for (let i = 0; i < formEleList.length; i++) {
        if (formEleList[i].type === 'grid') {
          formEleList[i].columns.forEach(item => {
            this.generateModel(item.list)
          })
        } else {
          const {model, options} = formEleList[i]
          if (this.value && Object.keys(this.value).indexOf(model) >= 0) {
            this.models[model] = this.value[model];
          } else {
            this.models[model] = options.defaultValue;
          }
          this.rules[model] = formEleList[i]['rules'];
        }
      }
    },
    getData() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          console.log(valid)
          if (valid) {
            resolve(this.models)
          } else {
            reject('error')
          }
        })
      })
    },
    handleChange(key, val){
      this.$emit('change', key, val, this.models)
    },
  },
  watch: {
    data: {
      deep: true,
      handler(val) {
        if (val) {
          this.generateModel(val.list)
        } else {
          this.models = {}
        }
      }
    },
    value: {
      deep: true,
      handler(val) {
        this.models = {...this.models, ...val};
      }
    }
  }
}
</script>

<style>

</style>
